package com.vitetest.api.repository;

import com.vitetest.api.entity.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    
    /**
     * 根据商品名称查找商品
     */
    Optional<Product> findByName(String name);
    
    /**
     * 根据商品分类查找商品
     */
    List<Product> findByCategory(String category);
    
    /**
     * 根据商品分类和激活状态查找商品
     */
    List<Product> findByCategoryAndIsActiveTrue(String category);
    
    /**
     * 查找所有激活的商品
     */
    List<Product> findByIsActiveTrue();
    
    /**
     * 分页查找所有激活的商品
     */
    Page<Product> findByIsActiveTrue(Pageable pageable);
    
    /**
     * 根据商品名称模糊查询
     */
    @Query("SELECT p FROM Product p WHERE p.name LIKE %:name% AND p.isActive = true")
    List<Product> findByNameContainingAndIsActiveTrue(@Param("name") String name);
    
    /**
     * 根据价格范围查找商品
     */
    @Query("SELECT p FROM Product p WHERE p.price BETWEEN :minPrice AND :maxPrice AND p.isActive = true")
    List<Product> findByPriceBetweenAndIsActiveTrue(@Param("minPrice") java.math.BigDecimal minPrice, 
                                                   @Param("maxPrice") java.math.BigDecimal maxPrice);
    
    /**
     * 查找库存不足的商品（库存小于指定数量）
     */
    @Query("SELECT p FROM Product p WHERE p.stock < :stockThreshold AND p.isActive = true")
    List<Product> findByStockLessThanAndIsActiveTrue(@Param("stockThreshold") Integer stockThreshold);
    
    /**
     * 根据商品名称和分类查找商品
     */
    @Query("SELECT p FROM Product p WHERE p.name LIKE %:name% AND p.category = :category AND p.isActive = true")
    List<Product> findByNameContainingAndCategoryAndIsActiveTrue(@Param("name") String name, 
                                                                @Param("category") String category);
    
    /**
     * 统计各分类的商品数量
     */
    @Query("SELECT p.category, COUNT(p) FROM Product p WHERE p.isActive = true GROUP BY p.category")
    List<Object[]> countByCategory();
    
    /**
     * 查找所有商品分类
     */
    @Query("SELECT DISTINCT p.category FROM Product p WHERE p.category IS NOT NULL AND p.isActive = true")
    List<String> findAllCategories();
} 